package com.lin.service.impl;

import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lin.dto.UserDTO;
import com.lin.entity.User;
import com.lin.mapper.AdminMapper;
import com.lin.mapper.UserMapper;
import com.lin.service.AdminService;
import com.lin.vo.DataVO;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author Created by Lin Weihong
 * @Time on 2021/11/26 11:32
 */
@Service
public class AdminServiceImpl extends ServiceImpl<UserMapper, User> implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    QueryWrapper<User> wrapper;

    /**
     * 管理员登录
     *
     * @param userDTO
     * @return
     */
    @Override
    public int login(UserDTO userDTO) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession();
        int flag = 0;
        //获得当前的用户
        Subject subject = SecurityUtils.getSubject();
        //封装用户的登录数据
        UsernamePasswordToken token = new UsernamePasswordToken(userDTO.getUserName(), SecureUtil.md5(userDTO.getPassword()));
        try {
            subject.login(token);
            wrapper = new QueryWrapper<>();
            wrapper.eq("user_name", userDTO.getUserName());
            User user = adminMapper.selectOne(wrapper);
            if (user.getRole() == 1) {
                session.setAttribute("user", user);
                flag = 1;
            } else {
                flag = 4;
            }
        } catch (UnknownAccountException e) {
            flag = 2;
        } catch (IncorrectCredentialsException e) {
            flag = 3;
        }
        return flag;
    }

    /**
     * 管理员查询所有用户
     *
     * @param page  页数
     * @param limit 条数
     * @return DataVO对象
     */
    @Override
    public DataVO<User> findData(Integer page, Integer limit) {
        //声明DataVO类
        DataVO<User> dataVO = new DataVO<>();
        dataVO.setCode(0);
        dataVO.setMsg("");
        IPage<User> iPage = new Page<>(page, limit);
        //QueryWrapper进行条件筛选，设置为null，则筛选出全部
        IPage<User> userIPage = adminMapper.selectPage(iPage, null);
        dataVO.setCount(userIPage.getTotal());
        List<User> userList = userIPage.getRecords();
        dataVO.setData(userList);
        return dataVO;
    }

    /**
     * 管理员添加用户
     *
     * @param user 接收到的实体
     * @return 添加结果
     */
    @Override
    public int addUser(User user) {
        //实例化一个User对象
        User myUser = new User();
        User dbUser = adminMapper.selectOne(wrapper.eq("user_name", user.getUserName()));
        if (dbUser != null) {
            //通过BeanUtils工具，将接收的对象赋值给myUser，因为我们需要对数据库的密码进行MD5加密
            BeanUtils.copyProperties(user, myUser, "password");
            //密码额外处理，采用md5加密
            myUser.setPassword(SecureUtil.md5(user.getPassword()));
            return adminMapper.insert(myUser);
        }else {
            return 2;
        }
    }

    /**
     * 管理员更新用户
     *
     * @param user
     * @return
     */
    @Override
    public boolean updateUser(User user) {
        User mUser = new User();
        BeanUtils.copyProperties(user, mUser, "password");
        mUser.setPassword(SecureUtil.md5(user.getPassword()));
        int update = adminMapper.updateById(mUser);
        if (update == 1) {
            return true;
        } else {
            return false;
        }
    }

}
